import { Pipe, PipeTransform, Injectable } from '@angular/core'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'

import { CurrencyService } from '@shared/services/currency.service'
import { numScale } from 'app/utils/helpers'

// i18n materials of payment brand is prefix with PAYMENT_BRAND.
@Pipe({ name: 'amtFormat' })
@Injectable({
  providedIn: 'root',
})
export class AmtFormatPipe implements PipeTransform {
  constructor(private currencyService: CurrencyService) {}

  transform(value: number, currency: string = ''): Observable<string> {
    return this.currencyService.getDecimalByCode(currency).pipe(
      map(digital => {
        const amt = numScale(value, -digital).toFixed(digital)
        return `${amt} ${currency}`
      }),
    )
  }

  transformTransAmt(value: number, currency: string = ''): Observable<string> {
    return this.currencyService.getDecimalByCode(currency).pipe(
      map(digital => {
        const amt = numScale(value, -digital).toFixed(digital)
        return `${amt}`
      }),
    )
  }

  parsePrice(value: string, currency: string = '', symbol: string = '', showCurrency: boolean = true) {
    return this.currencyService.getDecimalByCode(currency).pipe(
      map(digital => {
        value = parseFloat((value + '').replace(/[^\d\.-]/g, '')).toFixed(digital) + ''
        const l = value
          .split('.')[0]
          .split('')
          .reverse()
        const r = digital ? `.${value.split('.')[1]}` : ''
        let amt = ''
        for (const i of l) {
          amt += i
        }
        amt = amt
          .split('')
          .reverse()
          .join('')
        const str = `${symbol}${amt}${r}`
        return showCurrency ? str + ` ${currency}` : str
      }),
    )
  }

  transformPrice(value: number, currency: string = '', symbol: string = ''): Observable<string> {
    return this.currencyService.getDecimalByCode(currency).pipe(
      map(digital => {
        const amt = numScale(value, -digital).toFixed(digital)
        return `${symbol}${amt} ${currency}`
      }),
    )
  }
}
